#include "qnewdatadialog.h"
#include "ui_qnewdatadialog.h"

#include "../../libs/sharedLib/qnamevalidator.h"
#include "../../libs/sharedLib/qprojectcore.h"
#include "../../libs/sharedLib/qmemerymanager.h"
#include "../../libs/sharedLib/qvaluexml.h"
#include "../../libs/sharedLib/qvaluexml.h"

QNewDataDialog::QNewDataDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::QNewDataDialog),
    m_groupName(new SHAREDLIB::QNameEdit("[_a-zA-Z0-9.]{,64}")),
    m_name(new SHAREDLIB::QNameEdit("[_a-zA-Z0-9.]{,64}"))
{
    ui->setupUi(this);
    ui->horizontalLayout_2->addWidget(m_name,1);
    ui->groupCombo->setLineEdit(m_groupName);
    this->setProperty("no-ManhattanStyle",true);

    SHAREDLIB::QMemeryManager *m=SHAREDLIB::QProjectCore::getCore()->memeryManager();

    ui->typeCombo->addItems(SHAREDLIB::XMLValueFactory::supports());

    QString str;
    int count=m->dataCount();
    for(int i=0;i<count;i++)
    {
        str=m->getData(i)->property("group").toString();
        if(!m_groups.contains(str))
        {
            m_groups.append(str);
        }
    }
    ui->groupCombo->addItems(m_groups);

    m_name->setFocus();
}

QNewDataDialog::~QNewDataDialog()
{
    delete ui;
}

void QNewDataDialog::on_okBtn_clicked()
{
    QString group=m_groupName->value();
    QString name=m_name->value();
    QString type=ui->typeCombo->currentText();
    if(group=="" || name=="" || type=="")
    {
        return;
    }
    SHAREDLIB::QMemeryManager *m=SHAREDLIB::QProjectCore::getCore()->memeryManager();
    QObject* obj=new QObject;
    obj->setProperty("name",name);
    obj->setProperty("type",type);
    obj->setProperty("group",group);
    SHAREDLIB::XMLValue *v=SHAREDLIB::XMLValueFactory::create(type);
    if(v!=NULL)
    {
        obj->setProperty("data",v->value());
        delete v;
    }
    else
    {
        obj->setProperty("data","");
    }
    obj->setProperty("hold","false");
    obj->setProperty("save","0");
    m->addData(obj);
    close();
}

void QNewDataDialog::on_cancelBtn_clicked()
{
    close();
}

void QNewDataDialog::on_groupCombo_editTextChanged(const QString &arg1)
{
    if(m_groups.contains(arg1))
    {
        SHAREDLIB::QMemeryManager *m=SHAREDLIB::QProjectCore::getCore()->memeryManager();

        QString str;
        int count=m->dataCount();
        QStringList list;
        for(int i=0;i<count;i++)
        {
            str=m->getData(i)->property("group").toString();
            if(str==arg1)
            {
                list.append(m->getData(i)->property("name").toString());
            }
        }
        m_name->setIntermediateList(list);
    }
}
